package com.kyh.controller.api.sys;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kyh.enume.sys.ColEnum;
import com.kyh.enume.sys.MenuEnum;
import com.kyh.enume.sys.StatusEnum;
import com.kyh.properties.AppProps;
import com.kyh.service.sys.ColService;
import com.kyh.service.sys.MenuService;
import com.kyh.sys.entity.Col;
import com.kyh.sys.entity.Menu;
import com.kyh.sys.entity.Columns;
import com.kyh.sys.mapper.MenuMapper;
import com.kyh.util.CheckUtil;
import com.kyh.util.StringBoUtil;
import com.kyh.vo.BootstrapTableVoJA;
import com.kyh.vo.R;

@Controller
@RequestMapping("/api/inter/menu")
public class ApiInterMenuController {
	
	private static final Logger logger = Logger.getLogger(ApiInterMenuController.class);

	@Autowired
	private MenuMapper menuMapper;

	@Autowired
	private ColService colService;
	@Autowired
	private MenuService menuService;
	
	/*
	 * 一键添加字段
	 */
	@PostMapping("/addCols")
    @ResponseBody
	public R addCols(Model model, HttpServletRequest request, HttpServletResponse response,
			Long menuId
			){
		
		if (!CheckUtil.notNull(menuId)) {
			return R.error("ID不能为空");
		}

		Menu menu = menuMapper.get(menuId);
		if (menu.getMenuLev() != MenuEnum.Lev.TWO.value) {
			return R.error("非二级菜单不能添加字段");
		}
		
		// 获取字段列表
		Columns con = new Columns();
		String menuTable = menu.getMenuTable();
		if (menuTable.startsWith("sys_")) {
			con.setTableSchema(AppProps.get("admin.jdbc.databaseName"));
		} else {
			con.setTableSchema(AppProps.get("jdbc.databaseName"));
		}
		con.setTableName(menu.getMenuTable());
		List<Columns> listSyscolumn = con.queryList();

		for (Columns syscolumn : listSyscolumn) {
			String colCode = StringBoUtil.lowerFirst(StringBoUtil.replaceUnderLineAndUpperCase(syscolumn.getColumnName()));
			if (colCode.equals("createTime") || colCode.equals("updateTime")) {
				continue;
			}
			String dataType = syscolumn.getDataType().toLowerCase();

			// 确认字段类型
			Integer colType = ColEnum.ColType.TEXT.value;
			if (dataType.contains("time")) {
				colType = 5;
			}
			
			String colName = syscolumn.getColumnComment();
			Integer colSortNo = syscolumn.getOrdinalPosition().intValue() * 10;
			Integer colStatusShow = ColEnum.StatusShow.YES.value;
			Integer colStatusAdd = ColEnum.StatusAdd.YES.value;
			Integer colStatusEdit = ColEnum.StatusEdit.YES.value;
			Integer colStatusValidate = ColEnum.StatusValidate.NO.value;
			Integer colStatusSearch = ColEnum.StatusSearch.NO.value;
			String colSelectors = null;
			String colValueOnload = null;
			Integer colStatusListEdit = ColEnum.StatusListEdit.NO.value;
			String colScripts = "";
			String className = "";
			String fieldName = "";
			String placeholder = "";
			Integer status = StatusEnum.ON_USED.value;
			
			// 处理是否主键
			if (syscolumn.getOrdinalPosition() == 1) {
				colSortNo= 1;
				colStatusShow = ColEnum.StatusShow.NO.value;
				colStatusAdd = ColEnum.StatusAdd.NO.value;
				colStatusEdit = ColEnum.StatusEdit.NO.value;
			}
			
			// 处理status
			if ("status".equals(colCode)) {
				colName = "状态";
				colType = ColEnum.ColType.SELECTOR.value;
				colStatusShow = ColEnum.StatusShow.NO.value;
				colStatusAdd = ColEnum.StatusAdd.NO.value;
				colStatusEdit = ColEnum.StatusEdit.NO.value;
				colSelectors = "select dict_value as optionValue, dict_name as optionName from sys_dict where dict_key = 'status_int'";
			}
			
			// 处理字段名称
			if (colName == null || colName.length() == 0) {
				colName = "无";
			}
			
			Col entity = Col.col(
						menuId,
						colType,
						colCode,
						colName,
						colSortNo,
						colStatusShow,
						colStatusAdd,
						colStatusEdit,
						colStatusValidate,
						colStatusSearch,
						colSelectors,
						colValueOnload,
						colStatusListEdit,
						colScripts,
						className,
						fieldName,
						placeholder,
						status
						);
			
			try {
				colService.add(entity);
			} catch (Exception e) {
				logger.error(e);
			}
		}
		
		return R.ok("操作完成");
	}
	
	@RequestMapping("/search")
    @ResponseBody
	public BootstrapTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute Menu cond,
			Long roleId
			){
		
		if (roleId != null) {
			cond.where("A.menu_id in (select menu_id from sys_role_menu where role_id = " + roleId + " and status = 1)");
		}
		
		return menuService.search(cond);
	}
	
	@RequestMapping("/tree")
    @ResponseBody
	public R tree(Model model, HttpServletRequest request, HttpServletResponse response
			){
		
		return menuService.tree();
	}
}